package de.axa.smartfix.monitoring.model;

import java.beans.PropertyChangeEvent;
import java.io.File;
import java.util.Date;

public class PathMonitor extends AbstractMonitor {

	private int count;

	private File path;

	private String extension;

	private Date oldest;

	public PathMonitor() {
		this.count = 0;
		this.oldest = IMonitor.NO_DATE_AVAILABLE;
	}

	@Override
	public int getCount() {
		return this.count;
	}

	@Override
	public void update() {
		searchFiles();
	}

	private void searchFiles() {
		int newCount = 0;
		Date newDate = IMonitor.NO_DATE_AVAILABLE;

		for (File file : this.path.listFiles()) {
			if (file.isFile()
					&& file.getName().endsWith(this.extension)) {
				Date currentDate = new Date(file.lastModified());
				if (newDate == IMonitor.NO_DATE_AVAILABLE
						|| currentDate.before(newDate))
					newDate = currentDate;
				++newCount;
			}
		}

		setCount(newCount);
		setOldest(newDate);
	}

	@Override
	public Date getOldest() {
		return this.oldest;
	}

	private void setCount(int count) {
		PropertyChangeEvent pe = new PropertyChangeEvent(this, PROPERTY_COUNT,
				this.count, count);
		this.count = count;
		fireEvent(pe);
	}

	private void setOldest(Date oldest) {
		PropertyChangeEvent pe = new PropertyChangeEvent(this, PROPERTY_OLDEST,
				this.oldest, oldest);
		this.oldest = oldest;
		fireEvent(pe);
	}

	public String getExtension() {
		return extension;
	}

	public void setExtension(String extension) {
		this.extension = extension;
	}

	public File getPath() {
		return path;
	}

	public void setPath(File path) {
		this.path = path;
	}

}
